package com.erpanderp.wam.usm.view.timesheet;

import java.io.Serializable;
import java.text.DateFormatSymbols;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.TimeZone;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.faces.event.AjaxBehaviorEvent;
import javax.faces.event.MethodExpressionActionListener;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Row;
import org.primefaces.component.menubutton.MenuButton;
import org.primefaces.component.menuitem.MenuItem;
import org.primefaces.context.RequestContext;

import com.erpanderp.wam.ac.model.entity.project.ProjectAssignmentDetail;
import com.erpanderp.wam.adm.model.entity.Role;
import com.erpanderp.wam.adm.model.service.RolePermissionDAO;
import com.erpanderp.wam.usm.model.entity.projectandassignment.EmployeeProject;
import com.erpanderp.wam.usm.model.entity.projectandassignment.Project;
import com.erpanderp.wam.usm.model.entity.timesheet.ProjectAssignmentTimesheetDetail;
import com.erpanderp.wam.usm.model.entity.timesheet.Timesheet;
import com.erpanderp.wam.usm.model.entity.timesheet.TimesheetDetail;
import com.erpanderp.wam.usm.model.entity.user.Employee;
import com.erpanderp.wam.usm.model.entity.user.EmployeeAndReporting;
import com.erpanderp.wam.usm.model.entity.user.WAMUser;
import com.erpanderp.wam.usm.model.service.leave.EmployeeLeaveDAO;
import com.erpanderp.wam.usm.model.service.projectandassignment.EmployeeProjectDAO;
import com.erpanderp.wam.usm.model.service.timesheet.ProjectAssignmentTimesheetDetailDAO;
import com.erpanderp.wam.usm.model.service.timesheet.TimesheetDAO;
import com.erpanderp.wam.usm.model.service.timesheet.TimesheetDetailDAO;
import com.erpanderp.wam.usm.model.service.user.EmployeeAndReportingDAO;
import com.erpanderp.wam.usm.model.service.user.EmployeeDAO;
import com.erpanderp.wam.usm.model.service.user.EmployeeRoleDAO;
import com.erpanderp.wam.util.CommonLookup;
import com.erpanderp.wam.util.ValidationUtil;
import com.erpanderp.wam.util.WAMUtil;
import com.sun.org.apache.bcel.internal.generic.NEW;

@ManagedBean
@ViewScoped
public class SecurityInterfaceBean implements Serializable {

	HttpSession session = (HttpSession) FacesContext.getCurrentInstance()
			.getExternalContext().getSession(true);
	private WAMUser wamUser = (WAMUser) session
			.getAttribute(CommonLookup.SESSION_ATTRIBUTE_WAMUSER);
   private TimesheetDetail timesheetDetail = new TimesheetDetail();
   EmployeeDAO employeeDAO; 
   private String security;
   private List<TimesheetDetail> timeSheetDetailsList = new ArrayList<TimesheetDetail>(); 
   private SimpleDateFormat yearFormatter = new SimpleDateFormat("yyyy");
   private SimpleDateFormat monthFormatter = new SimpleDateFormat("MMMM");
   private Date timesheetDate = new Date();
 
   Calendar calendar = Calendar.getInstance();
   private String dayOfWeek;
   private boolean FORM_VALID;
   SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yyyy");
  
   TimesheetDetailDAO timesheetDetailDAO = new TimesheetDetailDAO(); 
   private List<TimesheetDetail> timesheetDetails = new LinkedList<TimesheetDetail>();
   private Timesheet timesheet = new Timesheet();
   WAMUtil wamUtil = new WAMUtil();
   private String selectedMonth; //selected timesheet month
   private boolean IN_PROJECT;
   EmployeeProjectDAO employeeProjectDAO = new EmployeeProjectDAO();
  private boolean INVALIDATE_TIME_FOUND;
   private String selectedMonthYear;
   private String securityPerson;
   
	public SecurityInterfaceBean() {
		timesheetDetails = timesheetDetailDAO.getTimesheetDetails(timesheetDate);
	}


	
	public String saveEmployeeLogs() throws ParseException{
		
	
		validate();
		if(FORM_VALID){
		calendar.setTime(timesheetDate);
		int dayOfTheWeek = calendar.get(Calendar.DAY_OF_WEEK);
		System.out.println("------------------DAY OF THE WEEK "+dayOfTheWeek);
		 
		
		timesheetDetailDAO.updateTimesheetDetails(timesheetDetails);
		
		FacesContext.getCurrentInstance().addMessage(null,new FacesMessage(FacesMessage.SEVERITY_WARN,
					" Data saved successfully.",
					""));
			 
			
		
		
		}else{
			System.out.println("FORM NOT VALID");
		}
		
		return null;
		
	}
	




	public void dateChanged(AjaxBehaviorEvent e){
		System.out.println("Date Changed...");
		System.out.println(timesheetDate);
		timesheetDate = (Date) ((org.primefaces.component.calendar.Calendar)e.getComponent()).getValue();
		timesheetDetails = timesheetDetailDAO.getTimesheetDetails(timesheetDate);
	}
	
	public boolean validate() throws ParseException {
		System.out.println("IN VALIDATE METHOD");
		FORM_VALID = true;
		
		Date currentDate = new Date();
        String stringCurrentDate = sdf.format(currentDate);
        Date parsedDate = sdf.parse(stringCurrentDate);
        Date timeSheetDate = timesheetDate;
		if (ValidationUtil.isEmpty((timeSheetDate == null) ? null : timeSheetDate.toString(), "Date",
				null, FacesContext.getCurrentInstance()) != null) {
			System.out.println("DATE IS EMPTY");

			FORM_VALID = false;

		}else if(timeSheetDate.compareTo(parsedDate) > 0){
			System.out.println("TIMESHEET DATE is after CURRENT DATE");
			FacesContext.getCurrentInstance().addMessage(
					null,
					new FacesMessage(FacesMessage.SEVERITY_WARN,
							"Selected date should be before or equal to today date", ""));
			FORM_VALID = false;
		}
		
		
		
		
        
		if (ValidationUtil.isEmpty(securityPerson, "Security person name", null,
				FacesContext.getCurrentInstance()) != null) {
			FORM_VALID = false;
			System.out.println("FORM-VLD:SECURITY PERSON" + FORM_VALID);
		}
       for(TimesheetDetail timesheetDetail : this.timesheetDetails){

			
			if(!timesheetDetail.getDayOfWeek().equals("Sunday") && !timesheetDetail.getDayOfWeek().equals("Saturday")){
				
				
				boolean INVALID_TIME_FOUND = false;
				if(ValidationUtil.isEmpty(timesheetDetail.getInTimeString(), "In Time ", "In Time ", FacesContext.getCurrentInstance()) != null){
					FORM_VALID = false;
					INVALID_TIME_FOUND = true;
				}else if(ValidationUtil.validate24HoursTime(timesheetDetail.getInTimeString(), "In Time", "", FacesContext.getCurrentInstance()) != null){
					FORM_VALID = false;
					INVALID_TIME_FOUND = true;
				}
				
				if(ValidationUtil.isEmpty(timesheetDetail.getOutTimeString(), "Out Time ", "Out Time ", FacesContext.getCurrentInstance()) != null){
					FORM_VALID = false;
					INVALID_TIME_FOUND = true;
				}else if(ValidationUtil.validate24HoursTime(timesheetDetail.getOutTimeString(), "Out Time", "", FacesContext.getCurrentInstance()) != null){
					FORM_VALID = false;
					INVALID_TIME_FOUND = true;
				}
				
				if(!INVALID_TIME_FOUND){
					String timeDiff = ValidationUtil.getTimeDifference(timesheetDetail.getInTimeString(), timesheetDetail.getOutTimeString(), "");
					if(timeDiff != null && timeDiff.equals("INVALID TIMES")){
						FORM_VALID = false;
						INVALID_TIME_FOUND = true;					
					}else{
						System.out.println("Diff: " + timeDiff);
						timesheetDetail.setDuration(timeDiff);
					}
				}
			}else{
				boolean INVALID_TIME_FOUND = false;
				
				if(ValidationUtil.isEmpty(timesheetDetail.getInTimeString(), "In Time ", "In Time ", FacesContext.getCurrentInstance()) != null){
					timesheetDetail.setInTimeString("09:30");
				}else if(ValidationUtil.validate24HoursTime(timesheetDetail.getInTimeString(), "In Time", "", FacesContext.getCurrentInstance()) != null){
					FORM_VALID = false;
					INVALID_TIME_FOUND = true;
				}
				
				if(ValidationUtil.isEmpty(timesheetDetail.getOutTimeString(), "Out Time ", "Out Time ", FacesContext.getCurrentInstance()) != null){
					timesheetDetail.setOutTimeString("18:30");
				}else if(ValidationUtil.validate24HoursTime(timesheetDetail.getOutTimeString(), "Out Time", "", FacesContext.getCurrentInstance()) != null){
					FORM_VALID = false;
					INVALID_TIME_FOUND = true;
				}
				
				if(!INVALID_TIME_FOUND){
					String timeDiff = ValidationUtil.getTimeDifference(timesheetDetail.getInTimeString(), timesheetDetail.getOutTimeString(), "");
					if(timeDiff != null && timeDiff.equals("INVALID TIMES")){
						FORM_VALID = false;
						INVALID_TIME_FOUND = true;					
					}else{
						timesheetDetail.setDuration(timeDiff);
					}
				}
			}
			
		
		}
		
		
		
	
		return FORM_VALID;
	}
	
	/*public boolean validateTimesheeDetail(TimesheetDetail timesheetDetail){
		INVALIDATE_TIME_FOUND = true;
	if(ValidationUtil.isEmpty(timesheetDetail.getInTimeString(), "In Time ", "In Time ", FacesContext.getCurrentInstance()) != null){
		INVALIDATE_TIME_FOUND = false;
		
	}else if(ValidationUtil.validate24HoursTime(timesheetDetail.getInTimeString(), "In Time is", "", FacesContext.getCurrentInstance()) != null){
		INVALIDATE_TIME_FOUND = false;
	}
	
	if(ValidationUtil.isEmpty(timesheetDetail.getOutTimeString(), "Out Time ", "Out Time ", FacesContext.getCurrentInstance()) != null){
		INVALIDATE_TIME_FOUND = false;
		
	}else if(ValidationUtil.validate24HoursTime(timesheetDetail.getOutTimeString(), "Out Time is", "", FacesContext.getCurrentInstance()) != null){
		INVALIDATE_TIME_FOUND = false;
		
	}
	

	return INVALIDATE_TIME_FOUND;
	}
*/	
	public TimesheetDetail getTimesheetDetail() {
		return timesheetDetail;
	}
	public void setTimesheetDetail(TimesheetDetail timesheetDetail) {
		this.timesheetDetail = timesheetDetail;
	}



	public WAMUser getWamUser() {
		return wamUser;
	}



	public void setWamUser(WAMUser wamUser) {
		this.wamUser = wamUser;
	}



	public String getSecurity() {
		return security;
	}



	public void setSecurity(String security) {
		this.security = security;
	}




	public List<TimesheetDetail> getTimeSheetDetailsList() {
		return timeSheetDetailsList;
	}


	public void setTimeSheetDetailsList(List<TimesheetDetail> timeSheetDetailsList) {
		this.timeSheetDetailsList = timeSheetDetailsList;
	}



	public SimpleDateFormat getYearFormatter() {
		return yearFormatter;
	}


	public void setYearFormatter(SimpleDateFormat yearFormatter) {
		this.yearFormatter = yearFormatter;
	}


	public SimpleDateFormat getMonthFormatter() {
		return monthFormatter;
	}


	public void setMonthFormatter(SimpleDateFormat monthFormatter) {
		this.monthFormatter = monthFormatter;
	}



	public Date getTimesheetDate() {
		return timesheetDate;
	}


	public void setTimesheetDate(Date timesheetDate) {
		this.timesheetDate = timesheetDate;
	}



	public String getDayOfWeek() {
		return dayOfWeek;
	}


	public void setDayOfWeek(String dayOfWeek) {
		this.dayOfWeek = dayOfWeek;
	}


	public boolean isFORM_VALID() {
		return FORM_VALID;
	}


	public void setFORM_VALID(boolean fORM_VALID) {
		FORM_VALID = fORM_VALID;
	}


	


	public List<TimesheetDetail> getTimesheetDetails() {
		return timesheetDetails;
	}


	public void setTimesheetDetails(List<TimesheetDetail> timesheetDetails) {
		this.timesheetDetails = timesheetDetails;
	}


	public Timesheet getTimesheet() {
		return timesheet;
	}


	public void setTimesheet(Timesheet timesheet) {
		this.timesheet = timesheet;
	}


	public WAMUtil getWamUtil() {
		return wamUtil;
	}


	public void setWamUtil(WAMUtil wamUtil) {
		this.wamUtil = wamUtil;
	}


	public String getSelectedMonth() {
		return selectedMonth;
	}


	public void setSelectedMonth(String selectedMonth) {
		this.selectedMonth = selectedMonth;
	}


	public boolean isIN_PROJECT() {
		return IN_PROJECT;
	}


	public void setIN_PROJECT(boolean iN_PROJECT) {
		IN_PROJECT = iN_PROJECT;
	}


	


	public String getSelectedMonthYear() {
		return selectedMonthYear;
	}


	public void setSelectedMonthYear(String selectedMonthYear) {
		this.selectedMonthYear = selectedMonthYear;
	}



	public String getSecurityPerson() {
		return securityPerson;
	}



	public void setSecurityPerson(String securityPerson) {
		this.securityPerson = securityPerson;
	}



	public boolean isINVALIDATE_TIME_FOUND() {
		return INVALIDATE_TIME_FOUND;
	}



	public void setINVALIDATE_TIME_FOUND(boolean iNVALIDATE_TIME_FOUND) {
		INVALIDATE_TIME_FOUND = iNVALIDATE_TIME_FOUND;
	}






}
